import { getAsyncRoutes } from '@/api/routes';

// 按照路由中meta下的rank等级升序来排序路由
const ascending = arr => {
    return arr.sort(
        (a, b) => {
            return a?.meta?.rank - b?.meta?.rank;
        }
    );
};

/**
 * 将多级嵌套路由处理成一维数组
 * @param routesList 传入路由
 * @returns 返回处理后的一维路由
 */
const formatFlatteningRoutes = (routesList) => {
    if (routesList.length <= 0) return routesList;
    for (let i = 0; i < routesList.length; i++) {
        if (routesList[i].children) {
            routesList = routesList
                .slice(0, i + 1)
                .concat(routesList[i].children, routesList.slice(i + 1));
        }
    }
    return routesList;
};

/**
 * 一维数组处理成多级嵌套数组（三级及以上的路由全部拍成二级，keep-alive 只支持到二级缓存）
 * @param routesList 处理后的一维路由菜单数组
 * @returns 返回将一维数组重新处理成规定路由的格式
 */
const formatTwoStageRoutes = (routesList) => {
    if (routesList.length <= 0) return routesList;
    const newRoutesList = [];
    routesList.forEach((v) => {
        if (v.path === "/") {
            newRoutesList.push({
                component: v.component,
                name: v.name,
                path: v.path,
                redirect: v.redirect,
                meta: v.meta,
                children: []
            });
        } else {
            newRoutesList[0].children.push({ ...v });
        }
    });
    return newRoutesList;
};

// 过滤后端传来的动态路由 重新生成规范路由
const addAsyncRoutes = (arrRoutes) => {
    if (!arrRoutes || !arrRoutes.length) return;
    arrRoutes.forEach((v) => {
        if (v.redirect) {
            v.component = Layout;
        } else {
            if (v.meta.realPath) {
                v.component = modulesRoutes[`/src/views${v.meta.realPath}/index.vue`];
            } else {
                v.component = modulesRoutes[`/src/views${v.path}/index.vue`];
            }
        }
        if (v.children) {
            addAsyncRoutes(v.children);
        }
    });
    return arrRoutes;
};

// 初始化路由
const initRouter = (name) => {
    let router = this.$router
    return new Promise(resolve => {
        getAsyncRoutes({ name }).then(({ info }) => {
            if (info.length === 0) {
                this.$store.permission.changeSetting(info);
            } else {
                formatFlatteningRoutes(addAsyncRoutes(info)).map(
                    (v) => {
                        // 防止重复添加路由
                        if (
                            router.options.routes[0].children.findIndex(
                                value => value.path === v.path
                            ) !== -1
                        ) {
                            return;
                        } else {
                            // 切记将路由push到routes后还需要使用addRoute，这样路由才能正常跳转
                            router.options.routes[0].children.push(v);
                            // 最终路由进行升序
                            ascending(router.options.routes[0].children);
                            if (!router.hasRoute(v.name)) router.addRoute(v);
                        }
                        resolve(router);
                    }
                );
                this.$store.permission.changeSetting(info);
            }
            router.addRoute({
                path: "/:pathMatch(.*)",
                redirect: "/notfound"
            });
        });
    });
};

export {
    initRouter,
    ascending,
    formatFlatteningRoutes,
    formatTwoStageRoutes
}